import { getCodeMirror } from "../util/editor";
import { waitAnswerEditorWrapper } from "../util/editor/answer";

function addTailToEditor(text) {
    const content = `

---

> ${text}
`;

    const editor = getCodeMirror();
    if (!editor) { return; }

    const doc = editor.getDoc();
    const pos = { line: editor.lineCount() };
    doc.replaceRange(content, pos);
}

function createIcon(...classList) {
    if (!classList?.length) {
        classList = ["fa-solid", "fa-file-signature"];
    }
    const icon = document.createElement("i");
    icon.classList.add(...classList);
    return icon;
}

function createImageIcon(url) {
    const img = document.createElement("img");
    img.src = url;
    img.width = "100%";
    img.style.objectFit = "cover";
    img.style.position = "center";
    return img;
}

function getIconCreator(icon) {
    switch (typeof icon) {
        case "string":
            if (icon.includes("/")) {
                return () => createImageIcon(icon);
            } else {
                return () => createIcon(icon.split(","));
            }
        case "function":
            return icon;
        default:
            if (Array.isArray(icon)) {
                return () => createIcon(...icon);
            }
            return createIcon;
    }
}

function createIconButton(icon, title, fn) {
    const button = document.createElement("button");
    button.type = "button";
    button.classList.add("p-0", "b-0", "toolbar");
    button.title = title ?? "添加活动小尾巴";
    Object.assign(button.style, {
        background: "none",
        color: "#e44d26"
    });

    button.appendChild(getIconCreator(icon)());
    button.addEventListener("click", fn);

    const div = document.createElement("div");
    div.classList.add("toolbar-item-wrap");
    div.appendChild(button);
    return div;
}

export async function addAnswerTail(text, title, icon) {
    const editorWrap = await waitAnswerEditorWrapper();
    const toolbar = editorWrap.querySelector(".toolbar-wrap");
    const lastChild = toolbar.children[toolbar.children.length - 1];

    toolbar.insertBefore(
        (() => {
            const div = document.createElement("div");
            div.classList.add("toolbar-divider");
            return div;
        })(),
        lastChild
    );

    toolbar.insertBefore(createIconButton(icon, title, () => addTailToEditor(text)), lastChild);
}